# TS推流工具 Makefile

# 编译器设置
CC = gcc
CFLAGS = -Wall -Wextra -std=c99 -O2

# FFmpeg库设置
FFMPEG_LIBS = -lavformat -lavcodec -lavutil
PKG_CONFIG = pkg-config

# 检查是否有pkg-config，优先使用它来获取FFmpeg配置
ifeq ($(shell which pkg-config 2>/dev/null),)
    # 没有pkg-config，使用默认设置
    INCLUDES = 
    LIBS = $(FFMPEG_LIBS)
else
    # 使用pkg-config获取FFmpeg配置
    INCLUDES = $(shell $(PKG_CONFIG) --cflags libavformat libavcodec libavutil 2>/dev/null)
    LIBS = $(shell $(PKG_CONFIG) --libs libavformat libavcodec libavutil 2>/dev/null)
    # 如果pkg-config失败，回退到默认设置
    ifeq ($(LIBS),)
        INCLUDES = 
        LIBS = $(FFMPEG_LIBS)
    endif
endif

# 目标文件
TARGET = ts_push
SOURCE = ts_push.c
OBJECT = ts_push.o

# 默认目标
all: $(TARGET)

# 编译可执行文件
$(TARGET): $(OBJECT)
	@echo "链接 $(TARGET)..."
	$(CC) $(OBJECT) -o $(TARGET) $(LIBS)
	@echo "编译完成: $(TARGET)"

# 编译目标文件
$(OBJECT): $(SOURCE)
	@echo "编译 $(SOURCE)..."
	$(CC) $(CFLAGS) $(INCLUDES) -c $(SOURCE) -o $(OBJECT)

# 清理编译产物
clean:
	@echo "清理编译产物..."
	rm -f $(OBJECT) $(TARGET)
	@echo "清理完成"

# 安装（可选）
install: $(TARGET)
	@echo "安装 $(TARGET) 到 /usr/local/bin..."
	sudo cp $(TARGET) /usr/local/bin/
	@echo "安装完成"

# 卸载（可选）
uninstall:
	@echo "卸载 $(TARGET)..."
	sudo rm -f /usr/local/bin/$(TARGET)
	@echo "卸载完成"

# 运行测试（示例）
test: $(TARGET)
	@echo "运行测试..."
	@echo "请提供测试文件和目标URL:"
	@echo "例如: make run INPUT=test.mp4 OUTPUT=udp://127.0.0.1:1234"

# 运行程序（需要提供INPUT和OUTPUT参数）
run: $(TARGET)
	@if [ -z "$(INPUT)" ] || [ -z "$(OUTPUT)" ]; then \
		echo "错误: 请提供INPUT和OUTPUT参数"; \
		echo "使用方法: make run INPUT=输入文件 OUTPUT=输出URL"; \
		echo "例如: make run INPUT=test.mp4 OUTPUT=udp://127.0.0.1:1234"; \
		exit 1; \
	fi
	./$(TARGET) $(INPUT) $(OUTPUT)

# 调试版本
debug: CFLAGS += -g -DDEBUG
debug: clean $(TARGET)
	@echo "调试版本编译完成"

# 检查FFmpeg依赖
check-deps:
	@echo "检查FFmpeg依赖..."
	@if $(PKG_CONFIG) --exists libavformat libavcodec libavutil 2>/dev/null; then \
		echo "✓ FFmpeg库通过pkg-config找到"; \
		echo "  版本信息:"; \
		$(PKG_CONFIG) --modversion libavformat libavcodec libavutil; \
	else \
		echo "⚠ pkg-config未找到FFmpeg库，将使用默认链接参数"; \
		echo "  请确保已安装FFmpeg开发库"; \
	fi

# 显示帮助信息
help:
	@echo "TS推流工具 Makefile"
	@echo ""
	@echo "可用目标:"
	@echo "  all        - 编译程序（默认）"
	@echo "  clean      - 清理编译产物"
	@echo "  debug      - 编译调试版本"
	@echo "  install    - 安装到系统路径"
	@echo "  uninstall  - 从系统卸载"
	@echo "  test       - 显示测试说明"
	@echo "  run        - 运行程序（需要INPUT和OUTPUT参数）"
	@echo "  check-deps - 检查FFmpeg依赖"
	@echo "  help       - 显示此帮助信息"
	@echo ""
	@echo "使用示例:"
	@echo "  make                                    # 编译程序"
	@echo "  make clean                              # 清理"
	@echo "  make debug                              # 编译调试版本"
	@echo "  make run INPUT=test.mp4 OUTPUT=udp://127.0.0.1:1234  # 运行程序"
	@echo "  make check-deps                         # 检查依赖"

# 声明伪目标
.PHONY: all clean install uninstall test run debug check-deps help